from flask import Blueprint,request,redirect,session,render_template,jsonify
from utils import db

vi = Blueprint('view', __name__)

# 角色字典
role_dict ={
    1:{'text':'普通用户','cls':'primary'},
    2:{'text':'管理员','cls':'danger'},
        }
# 支付状态字典
bill_status_dict ={
        0:{'text':'未支付','cls':'danger'},
        1:{'text':'已支付','cls':'success'},
    }

# 首页
@vi.route('/')
def index():
    return render_template('login.html')

# 登录
@vi.route('/login' ,methods=['GET'])
def show_login():
    return render_template('login.html')

# 注册
@vi.route('/sign' ,methods=['GET'])
def show_sign():
    return render_template('sign.html')
# 登出
@vi.route('/logout' ,methods=['GET'])
def logout():
    session.clear() 
    return redirect('/login',code=302)


# 展示用户信息接口
@vi.route('/user/list',methods=['GET'])
def user_list():
    user_info =session.get('user_info')
    if user_info['role'] == 1:
        show_user_sql = "select * from user WHERE ID = %s"
        user_list = db.get_all(show_user_sql,[user_info['ID']])
    else:
        show_user_sql = "select * from user"
        user_list = db.get_all(show_user_sql,[])
    return render_template('user_list.html', user_list=user_list,role_dict=role_dict)

# 展示用户个人信息接口
@vi.route("/user/<ID>",methods = ['GET'])
def show_user_info_self(ID):
    user_self = db.get_one("select * from user WHERE ID = %s",[ID])
    return render_template('user.html',user_self=user_self,role_dict=role_dict)

# 搜索用户接口
@vi.route('/user/list/<remark>', methods=['GET'])
def search_user(remark):
    user_list = db.get_all("SELECT * FROM user WHERE remark LIKE %s", ['%' + remark + '%'])
    return render_template('user_list.html', user_list=user_list, role_dict=role_dict)

# 查询密码
@vi.route("/user/<ID>/password",methods = ['GET'])
def update_password(ID):
    sql = "select password from user where ID = %s"
    result = db.get_one(sql,[ID])
    return jsonify(result)

# 查询账单
@vi.route("/bill/list/<remark>",methods = ['GET'])
def search_bill(remark):
    sql = "select * from bill where remark like %s"
    bill_list = db.get_all(sql,remark)
    return render_template("bill_list.html",bill_list=bill_list,bill_status_dict=bill_status_dict)


